<?php


namespace app\common\model;
use app\common\facade\MakeBuilder;
use think\model;
use think\facade\Db;
class Category extends Base
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    public function module()
    {
        return $this->belongsTo('modular', 'moduleid');
    }

    /**
     * ajax验证用户名
     */
    public function ajaxCateadmin($categoryname,$id = 0){
        if(empty($categoryname)){
            return 1;
        }
        //组装where条件
        $where = array();
        $where[] = array('categoryname','=',$categoryname);
        if($id > 0){
            $where[] =  array('id','<>',$id);
        }
        return Db::name('category')->where($where)->find();
    }

    // 获取列表
    public static function getList($order = ['sort', 'id' => 'desc'])
    {
        $list = self::order($order)
            ->select();
        //dump($list);die;
        foreach ($list as $k => $v) {
            //dump($list[$k]['moduleid']);die;
            if ($list[$k]['moduleid']) {
                //dump($v);die;
                $v['moduleid'] = $v->module->getData('title');
                //dump($v['moduleid']);die;
            }
        }
        $list = category_tree($list->toArray());
        //dump($list);die;
        // 重设栏目名称
        foreach($list as &$ls){
            //dump($ls);die;
            $ls['cate_name'] = $ls['lcatname'];
        }
        // 渲染输出
        $result = [
            'total' => count($list),
            'per_page' => 10000,
            'current_page' => 1,
            'last_page' => 1,
            'data' => $list,
        ];
        return MakeBuilder::changeTableData($result, 'Category');
    }
}